package com.neusoft.neuiotms.common.repository.impl;

import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;

import com.neusoft.bizcore.web.jpa.repository.AbstractRepository;
import com.neusoft.bizcore.web.support.Searchable;
import com.neusoft.neuiotms.common.model.DictionaryType;
import com.neusoft.neuiotms.common.model.QDictionaryType;
import com.neusoft.neuiotms.common.repository.CustomizedDictionaryTypeRepository;
import com.querydsl.core.BooleanBuilder;
import com.querydsl.jpa.impl.JPAQuery;

public class CustomizedDictionaryTypeRepositoryImpl extends AbstractRepository
        implements CustomizedDictionaryTypeRepository {

    @Override
    public List<DictionaryType> findAll(final Searchable searchable) {
        final QDictionaryType qDictionaryDesc = QDictionaryType.dictionaryType;
        final BooleanBuilder where = this.buildWhere(searchable);
        final JPAQuery<DictionaryType> query = this.query().selectFrom(qDictionaryDesc);
        query.where(where);
        return query.fetch();
    }

    @Override
    public Page<DictionaryType> search(final Pageable pageable, final Searchable searchable) {
        final QDictionaryType qDictionaryDesc = QDictionaryType.dictionaryType;
        final BooleanBuilder where = this.buildWhere(searchable);
        final JPAQuery<DictionaryType> query = this.query().selectFrom(qDictionaryDesc);
        query.where(where);
        return super.search(query, pageable);
    }

    @Override
    protected Class<?> getModelClass() {
        return DictionaryType.class;
    }

    private BooleanBuilder buildWhere(final Searchable searchable) {
        final BooleanBuilder where = new BooleanBuilder();
        final QDictionaryType qDictionary = QDictionaryType.dictionaryType;
        if (!StringUtils.isEmpty(searchable.getStrValue("type"))) {
            where.and(super.containsStr(qDictionary.type, searchable, "type"));
        }
        if (!StringUtils.isEmpty(searchable.getStrValue("text"))) {
            where.and(super.containsStr(qDictionary.text, searchable, "text"));
        }

        return where;
    }
}
